# 第一章python速览
import collections
import json
import math
import os
import sys
from collections import deque
from enum import Enum
from urllib.parse import urlparse

from bs4 import BeautifulSoup

# 字符串 String
from pprint import pprint


def test_string():
    tax = 12.5 / 100
    price = 100.50
    s = 'Python World'

    # print(s[:2])
    # print(s[:5])
    #
    # print(len(s))
    # print("You are in 'detached HEAD' state " * 2)


# 列表 List
# basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
# basket.sort()
# print(basket)
def list_test():
    squares = [1, 4, 8, 16, 25, 2 ** 10]
    # print(squares[-1])
    # 切片操作返回包含请求元素的新列表
    # squares[:]

    print(f'切片改变前的squares = {squares} len={len(squares)}')

    squares[2:5] = [50, 60, 70]
    print(f'切片改变后的squares = {squares} len={len(squares)}')
    print('The value of i is', 256 * 256)


# 函数 Function
def fib(n):
    a, b = 0, 1
    result = []
    while a < n:
        result.append(a)
        a, b = b, a + b
        #   过程推导
        #        = 0, 1
        #        = 1, 1
        #        = 1, 2
        #        = 2, 3
        #        = 3, 5
        #        = 5, 8
        #        = 8, 13
        #        = 13,21
    return result


# for else 语句
def for_else():
    for n in range(2, 100):
        for x in range(2, n):
            if n % x == 0:
                print(n, 'equals', x, '*', n // x)
                break
        else:
            print(f'{n} is a prime number')


# for continue 语句
def for_continue(r):
    """for continue循环

    :param r: 循环次数
    :return: void
    """
    for num in range(r):
        if num % 2 == 0:
            print(f'Found an even number {num}')
            continue
        print(f'Found an odd number {num}')


def loop():
    """循环的技巧"""
    seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    l1 = list(enumerate(seasons))
    for k, v in l1:
        print(f'Key {k} value {v}')


def ask_ok(prompt, retries=4, reminder='Please try again!'):
    """这是一段描述函数使用的信息"""
    while True:
        ok = input(prompt + ' ')
        if ok.lower() in ('y', 'ye', 'yes'):
            print('End process')
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            print(f'Again! {retries}')
        retries -= 1
        if retries < 0:
            raise ValueError("Invalid user response")
        print(reminder)


def cheeseshop(kind, *arguments, **keywords):
    """剩余参数 **keywords

    """
    print(f'-- Do you havve any {kind}?')
    print(f"I'm sorry, we're all out of {kind}")
    for arg in arguments:
        print(arg)

    print('-' * 40)
    for k, v in keywords.items():
        print(k, ':', v)


# cheeseshop('Limburger', "It's very runny, sir", 'It\'s really very, Very runny, sir', shopkeeper="Michael Palin",
#            client="Jho", sektch="Cheese Shop Sketch")


def make_incrementor(n: int):
    """ Lambda 表达式

    f2 = make_incrementor(40)
    :param n: int
    :return: int
    """
    return lambda x: x + n


class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'


# Python 连接数据库 1 connect 2执行语句 3查看结果 mysql-connector
# 用列表实现堆栈

# deque数据类型与list操作方法相似,但是可以快速从两端添加或删除元素
queue = deque(['Eric', 'John', 'Michael'])
queue.append("Terry")
# 列表推导式 ——创建列表的方式更简洁
# squares = [x**2 for x in range(10)]
# squares = []
# for x in range(10):
#     squares.append(x**2) # x的平方
# [表达式 fox x in xx [判断（可选）]]
# [expression for x in xx [if x == True]]
# [print(i) for i in sorted(basket)]
# [print(i,end=', ') for i in reversed(basket)]

# Tuple 元组和序列 元组不可改变值和数量
# 列表和字符串都是 ·序列· 例如 索引和切片操作
tuple1 = 1234, 54321, 'hello!'

# Set 集合是由不重复元素组成的无序容器
set1 = {x for x in 'abrqlkwjeoiqjnalksjdlkasd' if x not in 'abc'}

tel = {'jack': 4098, 'sape': 3193}

# list(tel) 返回字典所有键的列表
# 序列对比 (1, 2, 3) == (1.0, 2.0, 3.0)  --> True

# 第五章 [数据结构](https://docs.python.org/zh-cn/3/tutorial/datastructures.html)
# 第六章 [模块](https://docs.python.org/zh-cn/3/tutorial/modules.html)
#
# import fibo 写法一
# from fibo import fib, fib2 写法二
# from fibo import * 导入模块内定义的所有名称 不推荐
# import fibo as f  as用法
# f.fib(10)

# fibo.fib2(100)
# 内置函数 dir() 用于查找模块定义的名称
# print(dir(builtins))


# 第七章 输入输出

# 格式化字符串字面值
fruit = 'apple'
print(f'I like eat {fruit}')
print(f'The value of pi is approximately {math.pi:.10f}')


# str() 函数返回供人阅读的值 , repr() 生成适于解释器读取的值
# s = 'Hello World!'
# print(str(s))
# print(repr(s))

# 使用 json 保存结构化数据
# x = {'name': 'python json module', 'version': '1.0.0'}
# json.dump(x, open('package.json', 'w'))

# 第八章 错误和异常
def exception_func():
    try:
        num = 10 * 1 / 0
    except ZeroDivisionError as z:
        print(z)

    # try else else语句在没有异常发生时执行
    try:
        pass
    except ValueError as e:
        print(e)
    else:
        print('no exception happened!')

    try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise

    def func():
        raise ConnectionError

    try:
        func()
    except ConnectionError as exc:
        raise RuntimeError('Failed to open database') from exc

    # try finally

    try:
        raise KeyboardInterrupt
    finally:
        print('Goodbye, world!')


# 第九章 类

# 迭代器
s = []
it = iter(s)
print(next(it)) # _T  Type -> [类型]

a = next(it)

type(a)

# 第十章 标准库
